//1.引入vue
// import Vue from 'vue'
//2.引入axios库
import axiosNew from 'axios'
import { config } from '@/utils/config' //引入公用文件

axiosNew.defaults.timeout = 3000 //请求超时时间
axiosNew.defaults.baseURL = 'http://127.0.0.1:7001'
axiosNew.defaults.headers.post['Content-Type'] = 'application/json' //配置请求头

axiosNew.interceptors.request.use(
    //请求拦截
    (config) => {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        let token = sessionStorage.getItem('token')
        if (token) {
            //如果有token给请求头加上
            config.headers.common['token'] = token
        }
        return config
    },

    (err) => {
        return Promise.reject(err)
    }
)

axiosNew.interceptors.response.use(
    (response) => {
        //相应拦截
        console.log(response)
        return response
    },
    (err) => {
        return Promise.reject(err)
    }
)
const axios = function ({ path, method = 'GET', data = {} }: any = {}) {
    return new Promise((resolve, reject) => {
        let datas: object = { params: { ...data } }
        if (method === 'POST') datas = { ...{ data } }
        axiosNew({
            url: `${config.host}${path}`,
            method,
            ...datas,
        })
            .then((res) => {
                resolve(res.data)
            })
            .catch((err) => {
                resolve(-1)
            })
    })
}
export default axios
